package textExcel;

import java.util.Scanner;

public class TextExcel
{
	public static void main(String[] args)
	{
		Spreadsheet spreadsheet = new Spreadsheet();
		System.out.println(spreadsheet);
		
		Scanner keyboard = new Scanner(System.in);
		
		System.out.print("> ");
		
		while(keyboard.hasNextLine())
		{
			String command = keyboard.nextLine();
			handleCommand(command, spreadsheet);
			
			if(command.equals("quit"))
				break;
			
			System.out.print("> ");
		}
		
		keyboard.close();
	}
	
	public static void handleCommand(String command, Spreadsheet spreadsheet)
	{
		if(spreadsheet.isValidCell(command)) // print value of cell
		{
			System.out.println(spreadsheet.getCell(command));
			return;
		}
		
		if(command.equals("clear"))
		{
			spreadsheet.clear();
			System.out.println(spreadsheet);
			return;
		}
		
		if(command.startsWith("clear"))
		{
			if(spreadsheet.isValidCell(command.substring(6)))
			{
				spreadsheet.setCell(command.substring(6), new Cell());
				System.out.println(spreadsheet);
				return;
			}
			else
			{
				System.out.println("ERROR: Invalid command");
				return;
			}
		}
		
		if(command.contains("=")) // assign value to cell
		{
			// TODO: eliminate duplicate error prints (rearrange if statements)
			
			int equalsIndex = command.indexOf("=");
			
			if(equalsIndex < 3 || equalsIndex >= command.length() - 2
					|| command.length() < 6)
			{
				System.out.println("ERROR: Invalid command");
				return;
			}
			
			String cellReference = command.substring(0, equalsIndex - 1);
			String valueToAssign = command.substring(equalsIndex + 2);
			
			if(!spreadsheet.isValidCell(cellReference))
			{
				System.out.println("ERROR: Invalid command");
				return;
			}
			
			Cell newCell = null;
			
			try
			{
				newCell = new RealCell(Double.parseDouble(valueToAssign), spreadsheet);
			}
			catch(NumberFormatException e)
			{
				if(RealCell.isValidFormula(valueToAssign, spreadsheet))
					newCell = new RealCell(valueToAssign, spreadsheet);
				else if(MethodCell.isValidMethod(valueToAssign, spreadsheet))
					newCell = new MethodCell(valueToAssign, spreadsheet);
				else if(DateCell.getDate(valueToAssign) != null) // TODO: rewrite to call getDate() only once
					newCell = new DateCell(DateCell.getDate(valueToAssign));
				else if(StringCell.isValidString(valueToAssign))
					newCell = new StringCell(valueToAssign);
			}
			
			if(newCell != null)
			{
				spreadsheet.setCell(cellReference, newCell);
				System.out.println(spreadsheet);
			}
			else
				System.out.println("ERROR: Invalid command");
			
			return;
		}
	}
}
